import java.util.*;


public class JSCommands implements IJSCommands {

	private Map<String, Object> commandMap;
	
	public JSCommands() {
		
		commandMap = new HashMap<String, Object>();
		
		// Load all JSCommand objects to memory
		commandMap.put("mkdir", new MakeDir());
		commandMap.put("cd", new ChangeDir());
		commandMap.put("ls", new ListFiles());
		commandMap.put("pwd", new PresentWorkDir());
		commandMap.put("mv", new Move());
		commandMap.put("cp", new Copy());
		commandMap.put("cat", new Cat());
		commandMap.put("get", new Get());
		commandMap.put("echo", new Echo());
	
	}

	public String runCommand(String[] commandArray) {
		
		String commandNotFoundError = "%s: command not found";
		String result = new String();
		
		// If commandArray is empty, return the empty string
		// Else, handle the command, i.e. the first string in commandArray
		int commandLength = commandArray.length;
		if (commandLength != 0) {
			
			// Fetch the JSCommand object corresponding to the request
			String commandName = commandArray[0];
			JSCommand command = (JSCommand) commandMap.get(commandName);
			
			// Check if command exists and set result accordingly
			if (command == null) {
				result = String.format(commandNotFoundError, commandName);
			} else {
				
				// First line is the command
				result = commandName + "\n";
				
				// Second line is the rest of the arguments
				int i;
				for (i = 1; i < commandLength; i++) {
					result += commandArray[i] + " ";
				}
			
			}
			
		}
		
		return result;

	}
	
	public static void main(String[] args) {
		JSCommands jsc = new JSCommands();
		String[] commandArray1 = {"get", "arg1", "arg2"}; // Valid + arguments
		String[] commandArray2 = {"not-a-command", "arg1", "arg2"}; // Invalid + arguments
		String[] commandArray3 = {"cat"}; // Valid, no arguments
		String[] commandArray4 = {"not-a-command"}; // Invalid, no arguments
		System.out.println(jsc.runCommand(commandArray1));
		System.out.println(jsc.runCommand(commandArray2));
		System.out.println(jsc.runCommand(commandArray3));
		System.out.println(jsc.runCommand(commandArray4));
		System.out.println("End of test");
	}

}
